package de.homelabs.hlmodules.cms.configuration.service;

import java.util.ArrayList;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.springframework.stereotype.Service;

import de.homelabs.hlmodules.cms.api.configuration.service.IHLConfigurationManager;
import de.homelabs.hlmodules.cms.configuration.domain.HLConfigurationEntity;

@Service("hlConfigurationManager")
public class HLConfigurationManager implements IHLConfigurationManager {

	// vars
	Context initCtx;
	Context envCtx;

	private List<HLConfigurationEntity> configuration = new ArrayList<HLConfigurationEntity>();

	/**
	 * constructor
	 */
	public HLConfigurationManager() {
	}

	/**
	 * fired from Spring Framework after all properties of the class are set
	 * used to look for context-environment parameters (JNDI)
	 */
	public void afterPropertiesSet() throws Exception {
//		HLConfigurationEntity defaultConfig = new HLConfigurationEntity();
//		
//		try {
//			// create Context
//			initCtx = new InitialContext();
//			envCtx = (Context) initCtx.lookup("java:comp/env");
//			
//			// get properties from JNDI
//			defaultConfig = (HLConfigurationEntity) envCtx
//					.lookup("bean/HLConfiguration");
//			this.configuration.add(defaultConfig);
//		} catch (NamingException e) {
//			// we have a problem
//			defaultConfig.setHasErrors(true);
//			defaultConfig.addError(e.getLocalizedMessage());
//			this.configuration.add(defaultConfig);
//		}
	}

	/*******************
	 * getter / setter *
	 *******************/
	public HLConfigurationEntity getConfigurationByDomain(String domain) {
		for (HLConfigurationEntity e : configuration){
			if (e.getDomain().equalsIgnoreCase(domain))
				return e;
		}
		
		//not in list, try to load
		HLConfigurationEntity config = null;
		if ((config = contextLookup())!= null){
			//add domain
			config.setDomain(domain);
			
			//add to list
			this.configuration.add(config);
			
			//return
			return config;
		}
		
		//not found
		return null;
	}

	public List<HLConfigurationEntity> getConfiguratuion(){
		return configuration;
	}
	
	/********************
	 * functions		*
	 ********************/
	private HLConfigurationEntity contextLookup(){
		
		try {
			// create Context
			initCtx = new InitialContext();
			envCtx = (Context) initCtx.lookup("java:comp/env");
			
			// get properties from JNDI
			HLConfigurationEntity config = (HLConfigurationEntity) envCtx
					.lookup("bean/HLConfiguration");
			return config;
		} catch (NamingException e) {
			// we have a problem
			return null;
		}
	}
}
